﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using CodeCamp12.Domain;
using System.Web.Security;
using CodeCamp12.BLL;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using log4net;
using System.Reflection;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;



namespace CodeCamp12
{
    /// <summary>
    /// 
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [ScriptService]
    public class DataService : System.Web.Services.WebService
    {
        private ILog log = LogManager.GetLogger("CodeCamp12");

        #region Other

        [WebMethod]
        [ScriptMethod]
        public void UpdateContributors(string link)
        {
            var additionalBuissProvider = new AdditionalBL();
            try
            {
                additionalBuissProvider.UpdateContributors(link);
            }
            catch (Exception ex)
            {
                
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateFacebook(string link)
        {
            var additionalBuissProvider = new AdditionalBL();
            try
            {
                additionalBuissProvider.UpdateFacebook(link);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateTwitter(string link)
        {
            var additionalBuissProvider = new AdditionalBL();
            try
            {
                additionalBuissProvider.UpdateTwitter(link);
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateYouTube(string link)
        {
            var additionalBuissProvider = new AdditionalBL();
            try
            {
                additionalBuissProvider.UpdateYouTube(link);
            }
            catch (Exception ex)
            {
                 log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateLinkedin(string link)
        {
            var additionalBuissProvider = new AdditionalBL();
            try
            {
                additionalBuissProvider.UpdateLinkedin(link);
            }
            catch (Exception ex)
            {
                 log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public OtherProperties GetAdditionalStuff()
        {
            var additionalBuissProvider = new AdditionalBL();
            try
            {
                return additionalBuissProvider.GetAdditionalStuff();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
            
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateLogo()
        {
            var filename = HttpContext.Current.Request.Headers["X-File-Name"];

            Stream inputStream = null;
            try
            {
                if (filename == null)
                {
                    //This work for IE
                    try
                    {
                        HttpPostedFile uploadedfile = HttpContext.Current.Request.Files[0];
                        inputStream = uploadedfile.InputStream;
                    }

                    catch (Exception ex)
                    {
                         
                        log.Error(ex);
                        HttpContext.Current.Response.Write("{success:false}");
                    }

                    var additionalBuissProvider = new AdditionalBL();
                    additionalBuissProvider.UpdateLogo(inputStream);
                    HttpContext.Current.Response.Write("{success:true}");
                }

                else //Chrome Mozzila...
                {
                    try
                    {
                        inputStream = HttpContext.Current.Request.InputStream;
                    }
                    catch (Exception ex)
                    {
                         
                        log.Error(ex);

                        HttpContext.Current.Response.ContentType = "application/json";
                        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                        HttpContext.Current.Response.Write("{\"success\": \"false\"}");
                    }

                    var additionalBuissProvider = new AdditionalBL();
                    additionalBuissProvider.UpdateLogo(inputStream);

                    HttpContext.Current.Response.ContentType = "application/json";
                    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    HttpContext.Current.Response.Write("{\"success\": \"true\"}");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public string GetVideoUrl(string sessionId)
        {
            try
            {
                string[] sessionDirs =
                       Directory.GetDirectories(
                           HttpContext.Current.Request.PhysicalApplicationPath + "uploads\\FinishedSessions",
                           "*" + sessionId, SearchOption.AllDirectories);
                string[] files = Directory.GetFiles(sessionDirs[0], "*.wmv");
                if(files.Length != 0)
                {
                    FileInfo newFile = new FileInfo(files[0]);
                    return files[0].Replace(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty).Replace('\\', '/');    
                }
                else
                {
                    return String.Empty;
                }
                
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
                
            }
           
        }

        [WebMethod]
        [ScriptMethod]
        public void SendEmail(string name, string from, string subject, string messageText)
        {
           try
           {
               var fromAddress = "info@mkdot.net";
               var toAddress = "info@mkdot.net";
              
              
               var smtp = new System.Net.Mail.SmtpClient();
               {
                   smtp.Host = "casarray.ns.local";
                   smtp.Port = 25;
                   smtp.EnableSsl = false;
                   smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                   smtp.UseDefaultCredentials = true;
                   smtp.Timeout = 20000;
               }

               var body = "From: " + name + "\n";
               body += "Email: " + from + "\n";
               body += "Subject: " + subject + "\n";
               body += "Message: \n" + messageText + "\n";
               smtp.Send(fromAddress, toAddress, subject, body);
           }
           catch(Exception ex)
           {
               log.Error(ex);
               throw;
           }
        }

        #endregion

        #region Event

        [WebMethod]
        [ScriptMethod]
        public void InsertEvent(string eventName, DateTime startingFrom, DateTime endingAt, string location,
                                double latitude, double longitude)
        {
            var eventId = "";
            var eventNew = new Event
                               {
                                   EventName = eventName,
                                   StartingFrom = startingFrom,
                                   EndingAt = endingAt,
                                   Location = location,
                                   Latitude = latitude,
                                   Longitude = longitude
                               };
            var eventBuissProvider = new EventsBL();
            try
            {
               eventId = eventBuissProvider.InsertEvent(eventNew);
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            foreach (var titleChar in eventName)
            {
                if (titleChar.Equals('\\') || titleChar.Equals('/') || titleChar.Equals(':') || titleChar.Equals('*') || titleChar.Equals('?') || titleChar.Equals('"') || titleChar.Equals('<') || titleChar.Equals('>') || titleChar.Equals('|'))
                {
                    eventName = eventName.Replace(titleChar.ToString(), "");
                }
            }
            var folder = Server.MapPath("~/uploads/FinishedSessions/"+eventName+"$"+eventId);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateEvent(string eventId, string eventName, DateTime startingFrom, DateTime endingAt, string location,
                                double latitude, double longitude)
        {
            var eventBuissProvider = new EventsBL();
            try
            {
                if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx:UpdateEvent - eventId can not be null or empty");
                }
                else
                {
                    var eventNew = new Event
                    {
                        EventID = new Guid(eventId),
                        EventName = eventName,
                        StartingFrom = startingFrom,
                        EndingAt = endingAt,
                        Location = location,
                        Latitude = latitude,
                        Longitude = longitude
                    };
                    eventBuissProvider.UpdateEvent(eventNew);
                    
                    var eventFolders = Directory.GetDirectories(HttpContext.Current.Request.PhysicalApplicationPath + "uploads\\FinishedSessions", "*" + eventId);
                    var folderEventData = new DirectoryInfo(eventFolders[0]);
                    if(!eventName.Equals(folderEventData.Name.Split('$')[0]))
                    {
                        Directory.Move(eventFolders[0],Directory.GetParent(eventFolders[0]).FullName +"\\"+eventName+"$"+eventId);
                    }
                }
            }

            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }

            
        }

        [WebMethod]
        [ScriptMethod]
        public void DeleteEvent(string eventId)
        {
            var eventBuissProvider = new EventsBL();
            try
            {
                if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx : DeleteEvent - parametar eventId cannot be null or empty");
                }
                else
                {
                    var eventNew = new Event {EventID = new Guid(eventId)};
                    var sessionsForEvent = GetSessionsForEvent(eventId);
                    if(sessionsForEvent != null)
                    {
                        foreach (var session in sessionsForEvent)
                        {
                            DeleteSession(session.ID.ToString());
                        }
                    }
                    eventBuissProvider.DeleteEvent(eventNew);
                    var dirs = Directory.GetDirectories(HttpContext.Current.Request.PhysicalApplicationPath + "uploads\\FinishedSessions", "*" + eventId);
                    Directory.Delete(dirs[0]);
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }

           
        }

        [WebMethod]
        [ScriptMethod]
        public Event GetLocationForCurrentEvent()
        {
            var eventsBuissProvider = new EventsBL();
            try
            {
                return eventsBuissProvider.GetLocationForCurrentEvent();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
            
        }


        [WebMethod]
        [ScriptMethod]
        public List<Event> GetAllEvents()
        {
            var eventBuissProvider = new EventsBL();
            try
            {
                return eventBuissProvider.GetAllEvents();
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            
        }

        [WebMethod]
        [ScriptMethod]
        public Event GetEventById(string id)
        {
            var eventBuissProvider = new EventsBL();
            try
            {
                if(id.Equals(string.Empty))
                {
                    throw new Exception("DataService.asmx:GetEventById - parametar id can not be null or empty");
                }
                else
                {
                    return eventBuissProvider.GetEventById(new Guid(id));
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public Event GetCurrentEvent()
        {
            var eventBuissProvider = new EventsBL();
            try
            {
                return eventBuissProvider.GetCurrentEvent();
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void InsertSessionInTimeSlotInTrack(string sessionId, string timeSlotId, string trackId)
        {
            var buissProvider = new EventsBL();
            try
            {
                if(String.IsNullOrEmpty(sessionId))
                {
                    throw new Exception("In DataService.asmx : InsertSessionInTimeSlotInTrack - parametar sessionId can not be null or empty");
                }
                else if(String.IsNullOrEmpty(timeSlotId))
                {
                    throw new Exception("In DataService.asmx : InsertSessionInTimeSlotInTrack - parametar timeSlotId can not be null or empty");
                }
                else if(String.IsNullOrEmpty(trackId))
                {
                    throw new Exception("In DataService.asmx : InsertSessionInTimeSlotInTrack - parametar trackId can not be null or empty");
                }
                else
                {
                    buissProvider.InsertSessionInTimeSlotInTrack(new Guid(sessionId), new Guid(timeSlotId), new Guid(trackId));    
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }
        
        [WebMethod]
        [ScriptMethod]
        public void SetEventToCurrent(string eventId)
        {
            var buissProvider = new EventsBL();
            try
            {
                if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataServise.asmx : SetEventToCurrent - parametar eventId can not be null or empty");
                }
                else
                {
                    buissProvider.SetEventToCurrent(new Guid(eventId));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
        
        [WebMethod]
        [ScriptMethod]
        public void SetEventToFinished(string eventId)
        {
            var buissProvider = new EventsBL();
            try
            {
                if (String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataServise.asmx : SetEventToFinished - parametar eventId can not be null or empty");
                }
                else
                {
                    buissProvider.SetEventToFinished(new Guid(eventId));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
        

        #endregion

        #region Announcement

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void InsertAnnouncement(string title, DateTime date, string description)
        {
            try
            {
               var announcementBuissProvider = new AnnouncementsBL();
               var membershipUser = Membership.GetUser();
               if (membershipUser != null)
               {
                    var announcement = new Announcements
                                            {
                                                Title = title,
                                                Date = date,
                                                UserID = new Guid(membershipUser.ProviderUserKey.ToString()),
                                                Description = description
                                            };
                    announcementBuissProvider.InsertAnnouncement(announcement);
               }
               else
               {
                    throw new Exception("DataService.asmx : InsertAnnouncement User not logged in");
               }
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void UpdateAnnouncement(string id, string title, DateTime date, string description)
        {
            try
            {
                if (!String.IsNullOrEmpty(User.Identity.Name) && !String.IsNullOrEmpty(id))
                {
                    var announcementsBuissProvider = new AnnouncementsBL();
                    var announcement = new Announcements
                                           {
                                               Title = title,
                                               Date = date,
                                               UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString()),
                                               Description = description,
                                               ID = new Guid(id)
                                           };
                    announcementsBuissProvider.UpdateAnnouncement(announcement);
                }
                else
                {
                    throw new Exception(
                        "DataService.asmx : UpdateAnnouncement ID cannot be null or empty or user not logged in");
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void InsertNotification(string Title, DateTime Date, string Description, string Link)
        {
            try
            {
                if (!String.IsNullOrEmpty(User.Identity.Name))
                {
                    var announsmentsB = new AnnouncementsBL();
                    var notification = new Notification
                                           {
                                               Title = Title,
                                               Date = Date,
                                               Description = Description,
                                               UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString()),
                                               Link = Link
                                           };
                    announsmentsB.InsertNotification(notification);
                }
                else
                {
                    throw new Exception("In DataService.asmx : InsertNotification - User not logged in");
                }
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void DeleteAnnouncement(string ID)
        {
            try
            {
                if (User.Identity.Name != "" && ID != "")
                {
                    var announcementsBuissProvider = new AnnouncementsBL();
                    var announcement = new Announcements {ID = new Guid(ID)};
                    announcementsBuissProvider.DeleteAnnouncement(announcement);
                }
                else if(String.IsNullOrEmpty(User.Identity.Name))
                {
                    throw new Exception("In DataService.asmx : DeleteAnnouncement - User must be logged in");
                }
                else if(String.IsNullOrEmpty(ID))
                {
                    throw new Exception("In DataService.asmx : DeleteAnnouncement - parametar ID can not be null or empty");
                }
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void DeleteNotification(string ID)
        {
            try
            {
                if (!String.IsNullOrEmpty(User.Identity.Name) && !String.IsNullOrEmpty(ID))
                {
                    var announcementBuissProvider = new AnnouncementsBL();
                    var notification = new Notification {ID = new Guid(ID)};
                    announcementBuissProvider.DeleteNotification(notification);
                }
                else if(String.IsNullOrEmpty(User.Identity.Name))
                {
                    throw new Exception("In DataService.asmx : DeleteNotification - User must be logged in");
                }
                else if(String.IsNullOrEmpty(ID))
                {
                    throw new Exception("In DataService.asmx : DeleteNotification - Parametar ID can not be null or empty");
                }
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public List<Announcements> GetAnnouncements()
        {
            var announcementBuissProvider = new AnnouncementsBL();
            try
            {
                return announcementBuissProvider.GetAllAnnouncements();
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public Announcements GetAnnouncementByID(string AnnouncementID)
        {
            var announcementBuissProvider = new AnnouncementsBL();
           
            try
            {
                return announcementBuissProvider.GetAnnouncementById(new Guid(AnnouncementID));
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        
        }

        [WebMethod]
        [ScriptMethod]
        public List<Notification> GetNotifications()
        {
            var announcementBuissProvider = new AnnouncementsBL();
            try
            {
                return announcementBuissProvider.GetAllNotifications();
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);  
                throw;
            }
            
        }


        #endregion

        #region Speaker

        [WebMethod]
        [ScriptMethod]
        public string InsertSpeaker(string FirstName, string LastName, string CompanyName, string Country,
                                    string ExpertIn, string Link, string Description)
        {
            var speakerBuissProvider = new SpeakersBL();
            var speaker = new Speaker
                              {
                                  FirstName = FirstName,
                                  LastName = LastName,
                                  CompanyName = CompanyName,
                                  Country = Country,
                                  ExpertIN = ExpertIn,
                                  Link = Link,
                                  Description = Description
                              };
            string id = "";
            try
            {
                id = speakerBuissProvider.InsertSpeaker(speaker);
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            return id;
        }

        [WebMethod]
        [ScriptMethod]
        public void DeleteSpeaker(String ID)
        {
            var speakerBuissProvider = new SpeakersBL();
            var speaker = new Speaker();

            try
            {
                if (!String.IsNullOrEmpty(ID))
                {
                    speaker.ID = new Guid(ID);
                    var sessionList = GetSessionsForSpeaker(ID);
                    if(sessionList != null)
                    {
                        foreach (var session in sessionList)
                        {
                            DeleteSession(session.ID.ToString());
                        }    
                    }
                    speakerBuissProvider.DeleteSpeaker(speaker);
                }
                else
                {
                    throw new Exception("In DataService.asmx : DeleteSpeaker - ID string cannot be null or empty");
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateSpeaker(string ID, string FirstName, string LastName, string CompanyName, string Country,
                                  string ExpertIn, string Link, string Description)
        {
            var speakerBuissProvider = new SpeakersBL();
            try
            {
                if (String.IsNullOrEmpty(ID))
                    throw new Exception("In DataService.asmx:UpdateSpeaker - ID cannot be null or empty");
                else
                {
                    var speaker = new Speaker
                                      {
                                          ID = new Guid(ID),
                                          FirstName = FirstName,
                                          LastName = LastName,
                                          CompanyName = CompanyName,
                                          Country = Country,
                                          ExpertIN = ExpertIn,
                                          Link = Link,
                                          Description = Description
                                      };
                    speakerBuissProvider.UpdateSpeaker(speaker);
                }

            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public List<Speaker> GetAllSpeakers()
        {
            List<Speaker> speakerList = null;
            var speakerBuissProvider = new SpeakersBL();
            try
            {
                speakerList = speakerBuissProvider.GetAllSpeakers();
            }
            catch(Exception ex)
            {
                log.Error(ex);
                throw;
            }
            return speakerList;
        }

        [WebMethod]
        [ScriptMethod]
        public List<Speaker> GetSpeakersForCurrent()
        {
            List<Speaker> speakerList = null;
            var speakerBuissProvider = new SpeakersBL();
            try
            {
                speakerList = speakerBuissProvider.GetSpeakersForCurrent();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
            return speakerList;
        }
        
        [WebMethod]
        [ScriptMethod]
        public List<Speaker> GetSpeakersForEvent(string eventId)
        {
            var speakerBuissProvider = new SpeakersBL();
            try
            {
                if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx : GetSpeakersForEvent - parametar eventId can not be null or empty");
                }
                else
                {
                    return speakerBuissProvider.GetSpeakersForEvent(new Guid(eventId));
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            
        }

        [WebMethod]
        [ScriptMethod]
        public Speaker GetSpeakerByID(string ID)
        {
            var speakerBuissProvider = new SpeakersBL();
            try
            {
                return speakerBuissProvider.GetSpeakerById(new Guid(ID));
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
         
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void UploadData()
        {
            var ID = HttpContext.Current.Request.QueryString["SpeakerID"];
            var flag = HttpContext.Current.Request.QueryString["insert"];
            var filename = HttpContext.Current.Request.Headers["X-File-Name"];
            var filetype = "";
            Stream inputStream = null;
            if (filename == null)
            {
                //This works for IE
                try
                {
                    var uploadedfile = HttpContext.Current.Request.Files[0];
                    filename = uploadedfile.FileName;
                    var extension = "";
                    for (var i = filename.Length - 1; i >= 0; i--)
                    {
                        if (filename[i].Equals('.'))
                            break;
                        extension = filename[i] + extension;
                    }
                    filetype = '.' + extension;
                    inputStream = uploadedfile.InputStream;
                }

                catch (Exception ex)
                {
                    log.Error(ex);
                    HttpContext.Current.Response.Write("{success:false}");
                }

                var speakerBuissProvider = new SpeakersBL();

                if (flag.Equals("true"))
                {
                    var document = new Domain.File
                                       {
                                           FileName = filename,
                                           FileType = filetype,
                                           FileData = inputStream,
                                           SpeakerID = new Guid(ID)
                                       };
                    speakerBuissProvider.InsertDocumentForSpeaker(document);
                }
                else
                {
                    var document = new Domain.File
                                       {
                                           FileName = filename,
                                           FileType = filetype,
                                           FileData = inputStream,
                                           SpeakerID = new Guid(ID)
                                       };
                    speakerBuissProvider.UpdateDocumentForSpeaker(document);
                }
                HttpContext.Current.Response.Write("{success:true}");
            }

            else
            {
                try
                {
                    inputStream = HttpContext.Current.Request.InputStream;
                    var extension = "";
                    for (var i = filename.Length - 1; i >= 0; i--)
                    {
                        if (filename[i].Equals('.'))
                            break;
                        extension = filename[i] + extension;
                    }

                    filetype = '.' + extension;
                }
                catch (Exception ex)
                {
                     
                    log.Error(ex);
                    HttpContext.Current.Response.ContentType = "application/json";
                    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    HttpContext.Current.Response.Write("{\"success\": \"false\"}");

                }
                var speakerBuissProvider = new SpeakersBL();
                if (flag.Equals("true"))
                {
                    var document = new Domain.File
                                       {
                                           FileName = filename,
                                           FileType = filetype,
                                           FileData = inputStream,
                                           SpeakerID = new Guid(ID)
                                       };
                    speakerBuissProvider.InsertDocumentForSpeaker(document);
                }
                else
                {
                    var document = new Domain.File
                                       {
                                           FileName = filename,
                                           FileType = filetype,
                                           FileData = inputStream,
                                           SpeakerID = new Guid(ID)
                                       };
                    speakerBuissProvider.UpdateDocumentForSpeaker(document);
                }

                HttpContext.Current.Response.ContentType = "application/json";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.Write("{\"success\": \"true\"}");
            }


        }

        [WebMethod]
        [ScriptMethod]
        public List<Speaker> GetSpeakersByName(string speakerName)
        {
            var speakerBuissProvider = new SpeakersBL();
            try
            {
                return speakerBuissProvider.GetSpeakersByName(speakerName);
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        #endregion

        #region Sponsor

        [WebMethod]
        [ScriptMethod]
        public List<SponsorType> GetAllSponsorTypes()
        {
            var sponsorBuissProvider = new SponsorsBL();
            try
            {
                return sponsorBuissProvider.GetAllSponsorTypes();
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
         

        }

        [WebMethod]
        [ScriptMethod]
        public string[] GetAllSponsors()
        {
            var sponsorBuissProvider = new SponsorsBL();
            var i = 0;
            List<Sponsor> sponsorList = null;
            try
            {
                sponsorList = sponsorBuissProvider.GetAllSponsors();
                var json = new string[sponsorList.Count];
                foreach (var s in sponsorList)
                {
                    var str = "{\"ID\" : \"" + s.ID.ToString() + "\", \"SponsorName\":\"" + s.SponsorName +
                                 "\", \"Link\" : \"" + s.LinkToWebSite + "\", \"SponsorType\" : \"" + s.SponsorTypeText +
                                 "\"}";
                    json[i] = str;
                    i++;
                }
                return json;
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
           

        }

        [WebMethod]
        [ScriptMethod]
        public void DeleteSponsor(string ID)
        {
            var sponsorBuissProvider = new SponsorsBL();
            var sponsor = new Sponsor();
            try
            {
                if (!String.IsNullOrEmpty(ID))
                {
                    sponsor.ID = new Guid(ID);
                    sponsorBuissProvider.DeleteSponsor(sponsor);
                }
                else
                {
                    throw new Exception("In DataService.asmx : DeleteSponsor ID cannot be null or empty");
                }
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateSponsorNoImage(string ID, string SponsorName, string LinkToSite, string SponsorType)
        {
            var sponsorBuissProvider = new SponsorsBL();
            var sponsor = new Sponsor
                              {
                                  ID = new Guid(ID),
                                  SponsorName = SponsorName,
                                  LinkToWebSite = LinkToSite,
                                  SponsorType = new Guid(SponsorType)
                              };
            try
            {
                if (String.IsNullOrEmpty(SponsorType))
                    throw new Exception("DataService.asmx : UpdateSponsorNoImage SponsorType cannot be null or empty");
                else if (String.IsNullOrEmpty(ID))
                    throw new Exception("DataService.asmx : UpdateSponsorNoImage ID cannot be null or empty");
                else
                    sponsorBuissProvider.UpdateSponsor(sponsor);
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void InsertUpdateSponsor()
        {
            var sponsorName = HttpContext.Current.Request.QueryString["SponsorName"];
            var linkToSite = HttpContext.Current.Request.QueryString["LinkToSite"];
            var sponsorType = HttpContext.Current.Request.QueryString["SponsorType"];
            var id = HttpContext.Current.Request.QueryString["ID"];
            var filename = HttpContext.Current.Request.Headers["X-File-Name"];

            Stream inputStream = null;
            try
            {
                if (filename == null)
                {
                    //This work for IE
                    try
                    {
                        HttpPostedFile uploadedfile = HttpContext.Current.Request.Files[0];
                        inputStream = uploadedfile.InputStream;
                    }

                    catch (Exception ex)
                    {
                         
                        log.Error(ex);
                        HttpContext.Current.Response.Write("{success:false}");
                    }

                    var sponsorBuissProvider = new SponsorsBL();
                    if (id.Equals("0"))
                    {
                        var sponsor = new Sponsor
                                          {
                                              SponsorName = sponsorName,
                                              SponsorType = new Guid(sponsorType),
                                              SponsorImage = inputStream,
                                              LinkToWebSite = linkToSite
                                          };
                        try
                        {
                            if (String.IsNullOrEmpty(sponsorType))
                                throw new Exception(
                                    "In DataService.asmx : InsertUpdateSponsor SponsorType cannot be null or empty");
                            else
                                sponsorBuissProvider.InsertSponsor(sponsor);

                        }
                        catch (Exception ex)
                        {
                             
                            log.Error(ex);
                            throw;
                        }
                        
                    }
                    else
                    {
                        var sponsor = new Sponsor
                                          {
                                              ID = new Guid(id),
                                              SponsorName = sponsorName,
                                              LinkToWebSite = linkToSite,
                                              SponsorType = new Guid(sponsorType),
                                              SponsorImage = inputStream
                                          };

                        try
                        {
                            if (String.IsNullOrEmpty(sponsorType))
                                throw new Exception(
                                    "In DataService.asmx : InsertUpdateSponsor SponsorType cannot be null or empty");
                            else if (String.IsNullOrEmpty(id))
                                throw new Exception("In DataService.asmx : InsertUpdateSponsor ID cannot be null or empty");
                            else
                                sponsorBuissProvider.UpdateSponsor(sponsor);
                        }
                        catch (Exception ex)
                        {
                             
                            log.Error(ex);
                            throw;
                        }
                        
                    }

                    HttpContext.Current.Response.Write("{success:true}");
                }

                else
                {
                    try
                    {
                        inputStream = HttpContext.Current.Request.InputStream;
                    }
                    catch (Exception ex)
                    {
                         
                        log.Error(ex);
                        HttpContext.Current.Response.ContentType = "application/json";
                        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                        HttpContext.Current.Response.Write("{\"success\": \"false\"}");
                    }

                    var sponsorBuissProvider = new SponsorsBL();
                    if (id.Equals("0"))
                    {
                        var sponsor = new Sponsor
                                          {
                                              SponsorName = sponsorName,
                                              SponsorType = new Guid(sponsorType),
                                              SponsorImage = inputStream,
                                              LinkToWebSite = linkToSite
                                          };
                        try
                        {
                            if (String.IsNullOrEmpty(sponsorType))
                                throw new Exception("DataService.asmx : InsertUpdateSponsor ID cannot be null or empty");
                            else
                                sponsorBuissProvider.InsertSponsor(sponsor);
                        }
                        catch (Exception ex)
                        {
                             
                            log.Error(ex);
                            throw;
                        }
                        
                    }
                    else
                    {
                        var sponsor = new Sponsor
                                          {
                                              ID = new Guid(id),
                                              SponsorName = sponsorName,
                                              LinkToWebSite = linkToSite,
                                              SponsorType = new Guid(sponsorType),
                                              SponsorImage = inputStream
                                          };
                        try
                        {
                            if (String.IsNullOrEmpty(sponsorType))
                                throw new Exception(
                                    "In DataService.asmx : InsertUpdateSponsor SponsorType cannot be null or empty");
                            else if (String.IsNullOrEmpty(id))
                                throw new Exception("In DataService.asmx : InsertUpdateSponsor ID cannot be null or empty");
                            else
                                sponsorBuissProvider.UpdateSponsor(sponsor);

                        }
                        catch (Exception ex)
                        {
                             
                            log.Error(ex);   
                            throw;
                        }
                        
                    }

                    HttpContext.Current.Response.ContentType = "application/json";
                    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    HttpContext.Current.Response.Write("{\"success\": \"true\"}");
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }


        [WebMethod]
        [ScriptMethod]
        public string GetSponsorByID(string id)
        {
            var sponsorBuissProvider = new SponsorsBL();
            Sponsor sponsor = null;
            try
            {
                sponsor = sponsorBuissProvider.GetSponsorById(id);
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            

            return "{\"ID\" : \"" + sponsor.ID.ToString() + "\", \"SponsorName\":\"" + sponsor.SponsorName + "\", \"Link\" : \"" +
                   sponsor.LinkToWebSite + "\", \"SponsorType\" : \"" + sponsor.SponsorType.ToString() + "\"}";
        }

        #endregion

        #region Session

        [WebMethod]
        [ScriptMethod]
        public void InsertSession(string title, string description, string eventId, string language, string speakers)
        {
            string sessionId = "";
            var speakersList = speakers.Split(',');
            var session = new Session();
            try
            {
                session.Title = title;
                session.Description = description;
                session.EventID = new Guid(eventId);
                session.Language = language;
                session.Speakers = new List<Speaker>();
                foreach (var s in speakersList)
                {
                    var speaker = new Speaker {ID = new Guid(s)};
                    session.Speakers.Add(speaker);

                }

                var sessionBuissProvider = new SessionsBL();
                sessionId = sessionBuissProvider.InsertSession(session);
                try
                {
                    foreach (string f in Directory.GetDirectories(HttpContext.Current.Request.PhysicalApplicationPath + "uploads\\FinishedSessions", "*" + eventId))
                    {
                        var splitted = f.Split('\\');
                        var neededString = splitted[splitted.Length - 1];
                        var newTitle = "";
                        newTitle = title.Length > 35 ? title.Substring(0, 35) : title;
                        foreach (var titleChar in newTitle)
                        {
                            if(titleChar.Equals('\\')||titleChar.Equals('/')||titleChar.Equals(':')||titleChar.Equals('*')||titleChar.Equals('?')||titleChar.Equals('"')||titleChar.Equals('<')||titleChar.Equals('>')||titleChar.Equals('|'))
                            {
                                newTitle = newTitle.Replace(titleChar.ToString(), "");
                            }
                        }
                        var folder = Server.MapPath("~/uploads/FinishedSessions/" + neededString + "/" + newTitle + "$" + sessionId);

                        if (!Directory.Exists(folder))
                        {
                            Directory.CreateDirectory(folder);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    sessionBuissProvider.DeleteSession(session);
                    throw;
                }
                
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }

        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateSession(string id, string title, string description, string eventId, string language, string speakers)
        {
            var speakersList = speakers.Split(',');
            var session = new Session();
            var sessionBuissProvider = new SessionsBL();
            try
            {
                if (String.IsNullOrEmpty(id))
                {
                    throw new Exception("In DataService.asmx:UpdateSession - parametar id can not be null or empty");
                }
                else
                {
                    session.ID = new Guid(id);
                    session.Title = title;
                    session.Description = description;
                    session.EventID = new Guid(eventId);
                    session.Language = language;
                    session.Speakers = new List<Speaker>();
                    foreach (var s in speakersList)
                    {
                        var speaker = new Speaker { ID = new Guid(s) };
                        session.Speakers.Add(speaker);
                    }
                    sessionBuissProvider.UpdateSession(session);

                    var dirPath = HttpContext.Current.Request.PhysicalApplicationPath + "uploads\\FinishedSessions";
                    var parentDirs = Directory.GetDirectories(dirPath, "*" + id, SearchOption.AllDirectories);
                    var parentDirsNew = Directory.GetDirectories(dirPath, "*" + eventId);

                    foreach (var parentDir in parentDirs)
                    {
                        DirectoryInfo parentDirOld = Directory.GetParent(parentDir);
                        var folderEventId = parentDirOld.Name.Split('$')[1];
                        var oldTitle = new DirectoryInfo(parentDir).Name.Split('$')[0];

                        if (!folderEventId.Equals(eventId))
                        {
                            Directory.Move(parentDir, parentDirsNew[0] + "\\" + title + "$" + id);
                        }
                        else if (!oldTitle.Equals(title))
                        {
                            Directory.Move(parentDir, parentDirOld + "\\" + title + "$" + id);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            
            
            

        }

        [WebMethod]
        [ScriptMethod]
        public void DeleteSession(string id)
        {
            var session = new Session();
            var sessionBuissProvider = new SessionsBL();
            try
            {
                if (String.IsNullOrEmpty(id))
                {
                    throw new Exception("In DataService.asmx:DeleteSession - parametar id can not be null or empty");
                }
                else
                {
                    session.ID = new Guid(id);
                    sessionBuissProvider.DeleteSession(session);
                    var s = Directory.GetDirectories(HttpContext.Current.Request.PhysicalApplicationPath + "uploads\\FinishedSessions", "*" + id, SearchOption.AllDirectories);
                    foreach (var s1 in s)
                    {
                        Directory.Delete(s1);
                    }

                }

            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }

           
        }

        [WebMethod]
        [ScriptMethod]
        public List<Session> GetAllSessions()
        {
            var sessionBuissProvider = new SessionsBL();
            
            try
            {
               return sessionBuissProvider.GetAllSessions();

            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void DeleteSessionFromTrack(string id)
        {
            var sessionBuissProvider = new SessionsBL();
            try
            {
                if(String.IsNullOrEmpty(id))
                {
                    throw new Exception("In DataServise.asmx : DeleteSessionFromTrack - parametar id can not be null or empty");
                }
                else
                {
                    var sessionId = new Guid(id);
                    sessionBuissProvider.DeleteSessionFromTrack(sessionId);
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public List<Session> GetSessionsForEvent(string eventId)
        {
            var sessionBuissProvider = new SessionsBL();
            List<Session> sessionList = null;

            try
            {
                if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx : GetSessionsForEvent - parametar eventId can not be null or empty");
                }
                else
                {
                    var e = new Event { EventID = new Guid(eventId) };
                    sessionList = sessionBuissProvider.GetSessionForEvent(e);    
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            return sessionList;
        }

        [WebMethod]
        [ScriptMethod]
        public List<Session> GetSessionsForCurrent()
        {
            var sessionBuissProvider = new SessionsBL();
            try
            {
                return sessionBuissProvider.GetSessionsForCurrent();
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            
           
        }

        [WebMethod]
        [ScriptMethod]
        public List<Session> GetSessionsForSpeaker(string speakerId)
        {
            var sessionBuissProvider = new SessionsBL();
            try
            {
                if(String.IsNullOrEmpty(speakerId))
                {
                    throw new Exception("In DataServise.asmx:GetSessionsForSpeaker, parametar speakerId can not be null or empty ");
                }
                else
                {
                    return sessionBuissProvider.GetSessionsForSpeaker(new Guid(speakerId));    
                }
                
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }

          
        }
        
        
        [WebMethod]
        [ScriptMethod]
        public List<Session> GetSessionsNotInTrack(string trackId, string eventId)
        {
            var sessionBuissProvider = new SessionsBL();
            try
            {
                if(String.IsNullOrEmpty(trackId))
                {
                    throw new Exception("In DataService.asmx:GetSessionsNotInTrack - parametar trackId can not be null or empty");
                    
                }
                else if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx:GetSessionsNotInTrack - parametar eventId can not be null or empty");
                }
                else
                {
                    return sessionBuissProvider.GetSessionNotInTrack(new Guid(trackId), new Guid(eventId));    
                }
                
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            
        }

        [WebMethod]
        [ScriptMethod]
        public List<Session> GetSessionsInTrack(string trackId, string eventId)
        {
            var sessionBuissProvider = new SessionsBL();
           
            try
            {
                if(String.IsNullOrEmpty(trackId))
                {
                    throw new Exception("In DataService.asmx:GetSessionsInTrack - parametar trackId can not be null or empty");
                }
                else if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx:GetSessionsInTrack - parametar eventId can not be null or empty");   
                }
                else
                {
                    return sessionBuissProvider.GetSessionInTrack(new Guid(trackId), new Guid(eventId));
                }
                

            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
            
        }

        [WebMethod]
        [ScriptMethod]
        public void InsertImagesForSession(string id, string url)
        {
            var sessionBuissProvider = new SessionsBL();
            try
            {
                if (String.IsNullOrEmpty(id))
                {
                    throw new Exception("In DataService.asmx:InsertImagesForSession - parametar id can not be null or empty");
                }
                else
                {
                    sessionBuissProvider.InsertImagesForSession(url, new Guid(id));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }

        
        [WebMethod]
        [ScriptMethod]
        public Session GetSessionById(string id)
        {
            var sessionBuissProvider = new SessionsBL();
            
            try
            {
                if(String.IsNullOrEmpty(id))
                {
                    throw new Exception("In DataServise.asmx : GetSessionById - parametar id can not be null or empty");
                }
                else
                {
                    return sessionBuissProvider.GetSessionById(new Guid(id));    
                }
                
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }

           
        }

        #endregion

        #region Track
        
        [WebMethod]
        [ScriptMethod]
        public void InsertTrack(string trackName, string trackColor, string description, string eventId)
        {
            var track = new Track();
            var trackBuissProvider = new TrackBL();
                try
                {
                    if (eventId == "")
                    {
                        throw new Exception("In DataService.asmx : InsertTrack - parametar eventId should not be null or empty");
                    }
                    else
                    {
                        track.TrackName = trackName;
                        track.TrackColor = trackColor;
                        track.Description = description;
                        track.EventID = new Guid(eventId);
                        trackBuissProvider.InsertTrack(track);
                    }
                }
                catch (Exception ex)
                {
                     
                    log.Error(ex);
                    throw;
                }
        }

        [WebMethod]
        [ScriptMethod]
        public void DeleteTrack(string trackId)
        {
            var track = new Track();
            var buissProvider = new TrackBL();

            try
            {
                if(String.IsNullOrEmpty(trackId))
                {
                    throw new Exception("In DataService.asmx:DeleteTrack - parametar trackId can not be null or empty");
                }
                else
                {
                    track.TrackID = new Guid(trackId);
                    buissProvider.DeleteTrack(track);
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public List<Track> GetAllTracks(string eventId)
        {
            var trackBuissProvider = new TrackBL();
            List<Track> tracks = new List<Track>();
            try
            {
                if(eventId.Equals(string.Empty))
                    throw new Exception("DataService.asmx:GetAllTracks argument eventId cannot be empty");
                else
                {
                    tracks = trackBuissProvider.GetAllTracks(new Guid(eventId));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
            return tracks;

        }

        #endregion

        #region TimeSlot

        [WebMethod]
        [ScriptMethod]
        public void InsertTimeSlot(DateTime from, DateTime to, string eventId, string type)
        {
            var slotBuissProvider = new TimeSlotBL();
            try
            {
                if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx : InsertTimeSlot - parametar eventId can not be null or empty ");
                }
                else
                {
                    var timeSlot = new TimeSlots {From = @from, To = to, EventID = new Guid(eventId), Type = type};
                    slotBuissProvider.InsertTimeSlot(timeSlot);
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }
        
        [WebMethod]
        [ScriptMethod]
        public List<TimeSlots> GetTimeSlotsForEvent(string eventId)
        {
            var buissProvider = new TimeSlotBL();
            try
            {
                if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx : GetTimeSlotsForEvent - parameter eventId can not be null or empty");
                }
                else
                {
                    return buissProvider.GetTimeSlotsForEvent(new Guid(eventId));
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }

         
        }

       

        [WebMethod]
        [ScriptMethod]
        public List<TimeSlots> GetTimeSlotsForTrack(string trackId, string eventId)
        {
            var buissProvider = new TimeSlotBL();
            try
            {
                if (String.IsNullOrEmpty(trackId))
                {
                    throw new Exception("In DataService.asmx : GetTimeSlotsForTrack - parameter trackId can not be null or empty");
                }
                else if(String.IsNullOrEmpty(eventId))
                {
                    throw new Exception("In DataService.asmx : GetTimeSlotsForTrack - parameter eventId can not be null or empty");
                }
                else
                {
                    return buissProvider.GetTimeSlotsForTrack(new Guid(trackId), new Guid(eventId));
                }
            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }

            
        }


        [WebMethod]
        [ScriptMethod]
        public void DeleteTimeSlot(string id)
        {
            var timeSlot = new TimeSlots();
            var buissProvider = new TimeSlotBL();
            try
            {
                if(String.IsNullOrEmpty(id))
                {
                    throw new Exception("In DataService.asmx : DeleteTimeSlots - parameter id can not be null or empty");
                }
                else
                {
                    timeSlot.ID = new Guid(id);
                    buissProvider.DeleteTimeSlot(timeSlot);
                }

            }
            catch (Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        [WebMethod]
        [ScriptMethod]
        public void UpdateTimeSlots(string eventId, string keynoteLink, string breakLink)
        {
            
            var buissProvider = new TimeSlotBL();
            try
            {
                if (String.IsNullOrEmpty(eventId))
                {
                    throw new Exception(
                        "In DataService.asmx : UpdateTimeSlots - parameter eventId can not be null or empty");
                }
                else
                {
                    buissProvider.UpdateTimeSlot(new Guid(eventId), keynoteLink, breakLink);
                }
            }
            catch(Exception ex)
            {
                 
                log.Error(ex);
                throw;
            }
        }

        #endregion
        
       
    }
}
